using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;

namespace CFree.Common.Script
{
    public class RawLuaLoader
    {
        private static List<string> searchPath;

        public static bool initSearchPath = false;
        private static bool caseSensitive = true;

        static void InitSearchPath()
        {
            searchPath = new List<string>();
            var patchRoot = $"{Application.persistentDataPath}/{"Patch"}";//PatchConfig.PatchRootName
            foreach (var luaRoot in LuaConst.LuaSearchRoots)
            {
                var patchRelativeDir = $"{patchRoot}/{luaRoot}";
                searchPath.Add(patchRelativeDir);
            }

            foreach (var luaRoot in LuaConst.LuaSearchRoots)
            {
                searchPath.Add($"{LuaConst.LuaDir}/{luaRoot}");
            }

            initSearchPath = true;
        }

        public static byte[] LoadFileAndroid(ref string filepath)
        {
            // TODO: 手机平台使用bundle加载，目前手机平台放在StreamingAssets下也用文件加载
            string truePath = "";
            foreach (string spath in searchPath)
            {
                truePath = spath + filepath.Replace('.', '/') + ".lua";
                //Debug.Log($"truePath: {truePath}");
                if (File.Exists(truePath))
                {
                    return File.ReadAllBytes(truePath);
                }

                if (truePath.Contains(Application.streamingAssetsPath))
                {
                    var webRequest = UnityWebRequest.Get(truePath);
                    webRequest.timeout = 1;
                    var operation = webRequest.SendWebRequest();

                    while (!operation.isDone) { }

                    var downloadHandler = webRequest.downloadHandler;
                    if (downloadHandler != null && webRequest.responseCode != 404)
                    {
                        Debug.Log($"UnityWebRequest RetCode: {webRequest.responseCode}");
                        return downloadHandler.data;
                    }
                }
            }
            Debug.LogError("***************** Lua file not exist! file:" + truePath);
            return null;
        }

        public static byte[] LoadFileIOS(ref string filepath)
        {
            foreach (string spath in searchPath)
            {
                var truePath = spath + filepath.Replace('.', '/') + ".lua";
                if (File.Exists(truePath))
                {
                    return File.ReadAllBytes(truePath);
                }
            }
            Debug.LogError("***************** Lua file not exist! file:" + filepath);
            return null;
        }

        public static byte[] LoadFileWin(ref string rawFilePath)
        {
            byte[] result = null;
            string truePath = "";
            foreach (string spath in searchPath)
            {
                //xlua的lua文件都是.txt文件,故需要加上.lua.txt后缀而不是.lua
                truePath = spath + rawFilePath.Replace(".", "/") + ".lua.txt";

                var f = new FileInfo(truePath);

                if (File.Exists(truePath))
                {
                    return File.ReadAllBytes(truePath);
                    //if (!caseSensitive)
                    //{
                    //    return File.ReadAllBytes(truePath);
                    //}
                    //else
                    //{
                    //    var pathItems = rawFilePath.Split('.');
                    //    var accPath = spath;
                    //    // 检查目录
                    //    for (int i = 0; i < pathItems.Length - 1; ++i)
                    //    {
                    //        string nonSensitiveDir = Path.Combine(accPath, pathItems[i]);
                    //        var dirs = Directory.GetDirectories(accPath, pathItems[i]);

                    //        if (nonSensitiveDir != dirs[0])
                    //        {
                    //            Debug.LogError("Directory path is CASE SENSITIVE, please check:" + nonSensitiveDir);
                    //            return null;
                    //        }
                    //        accPath = dirs[0];
                    //    }
                    //    // 检查文件名


                    //    string nonSensitivePath = Path.Combine(accPath, pathItems[pathItems.Length - 1] + ".lua");
                    //    var paths = Directory.GetFiles(accPath, Path.GetFileName(nonSensitivePath));
                    //    if (nonSensitivePath != paths[0])
                    //    {
                    //        Debug.LogError("File path is CASE SENSITIVE, please check:" + nonSensitivePath);
                    //        return null;
                    //    }


                    //    return File.ReadAllBytes(nonSensitivePath);
                    //}
                }
            }
            return result;
        }

        public static byte[] LoadFileOSX(ref string rawFilePath)
        {
            return LoadFileWin(ref rawFilePath);
        }

        public static byte[] LoadLuaFileFromBundle(string filePath)
        {
            foreach (string spath in LuaConst.LuaSearchRoots)
            {
                var truePath = spath + filePath.Replace('.', '/') + ".lua";
                //TextAsset luaFile = ResourceManager.Inst.LoadFileInScriptFolder(truePath) as TextAsset;
                //if (luaFile != null)
                //{
                //    return luaFile.bytes;
                //}
            }

            return null;
        }

        private static byte[] LoadLuaFromFile(ref string filePath)
        {
            if (Application.installMode == ApplicationInstallMode.Editor)
            {
                return LoadFileWin(ref filePath);
            }
            switch (Application.platform)
            {
                case RuntimePlatform.Android:
                    return LoadFileAndroid(ref filePath);
                case RuntimePlatform.IPhonePlayer:
                    return LoadFileIOS(ref filePath);
                case RuntimePlatform.WindowsEditor:
                    return LoadFileWin(ref filePath);
                case RuntimePlatform.WindowsPlayer:
                    return LoadFileWin(ref filePath);
                case RuntimePlatform.OSXEditor:
                    return LoadFileOSX(ref filePath);
                default:
                    Debug.Log("Cannot find loader " + Application.platform + " for file " + filePath);
                    break;
            }

            return null;
        }

        public static byte[] Load(ref string filepath)
        {
            if (!initSearchPath)
            {
                InitSearchPath();
            }

            //if (ResourceManager.IsBundleModeForScript)
            //{
            //    return LoadLuaFileFromBundle(filepath);
            //}
            return LoadLuaFromFile(ref filepath);
        }
    }
}
